package com.liujianlei.forum_system.service.impl;

import com.liujianlei.forum_system.common.ResultCode;
import com.liujianlei.forum_system.dao.BoardMapper;
import com.liujianlei.forum_system.exception.ApplicationException;
import com.liujianlei.forum_system.model.Board;
import com.liujianlei.forum_system.service.IBoardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author tongchen
 * @create 2023-06-08 10:35
 */
@Slf4j
@Service
public class IBoardServiceImpl implements IBoardService {
    //注入mapper
    @Resource
   private BoardMapper boardMapper;
    @Override
    public void create(Board board) {
        //不存在直接报错
        //判断board的存在性
        if(board==null){
            throw new ApplicationException(ResultCode.ERROR_IS_NULL.toString());
        }
        //插入之前判断是否存在
        Board exists = boardMapper.selectByName(board.getName());
        if(exists!=null){
            throw new ApplicationException(ResultCode.FAILED_CREATE.toString());
        }
        //存在board信息进行后续数据填充
        board.setArticleCount(0);//帖子数量
        board.setState((byte) 0);//帖子状态
        board.setDeleteState((byte)0);//是否删除
        //创建date对象
        Date date = new Date();
        board.setCreateTime(date);
        board.setUpdateTime(date);
        //使用mapper进行插入
        int result = boardMapper.insertSelective(board);
        if(result!=1){
            throw new ApplicationException(ResultCode.FAILED_CREATE.toString());
        }
        //没有报异常则说明插入成功
        log.info("插入成功");

    }

    @Override
    public List<Board> selectTopByNum(Integer num) {
        //检验参数有效性
        if(num<=0){
            //抛出异常
            throw new  ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //调用mapper方法
        List<Board> boards = boardMapper.selectTopByNum(num);
        return boards;
    }

    @Override
    public List<Board> selectAllNormal() {
        //调用mapper方法

        return boardMapper.selectAllNormal();
    }

    @Override
    public Board selectById(Long id) {
         return boardMapper.selectByPrimaryKey(id);
    }
}
